package cn.tedu.yushouge.pet.adopt.service.impl;

import cn.tedu.yushouge.commons.ex.ServiceException;
import cn.tedu.yushouge.commons.pojo.vo.PageData;
import cn.tedu.yushouge.commons.web.ServiceCode;
import cn.tedu.yushouge.pet.adopt.mapper.AdoptMapper;
import cn.tedu.yushouge.pet.adopt.mapper.AdoptRecordMapper;
import cn.tedu.yushouge.pet.adopt.mapper.PetMapper;
import cn.tedu.yushouge.pet.adopt.pojo.entity.Adopt;
import cn.tedu.yushouge.pet.adopt.pojo.entity.AdoptRecord;
import cn.tedu.yushouge.pet.adopt.pojo.param.AdoptAddNewParam;
import cn.tedu.yushouge.pet.adopt.pojo.param.AdoptUpdateInfoParam;
import cn.tedu.yushouge.pet.adopt.pojo.vo.AdoptListItemVO;
import cn.tedu.yushouge.pet.adopt.pojo.vo.AdoptListVO;
import cn.tedu.yushouge.pet.adopt.pojo.vo.AdoptStandardVO;
import cn.tedu.yushouge.pet.adopt.service.IAdoptService;
import cn.tedu.yushouge.commons.util.PageInfoToPageDataConverter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class AdoptServiceImpl implements IAdoptService {

    @Autowired
    AdoptMapper adoptMapper;

    @Autowired
    PetMapper petMapper;

    @Autowired
    AdoptRecordMapper adoptRecordMapper;

    @Override
    public void addNew(AdoptAddNewParam adoptAddNewParam) {
        log.debug("开始处理【添加宠物领养】的业务，参数：{}", adoptAddNewParam);
        QueryWrapper<Adopt> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pet_id",adoptAddNewParam.getPetId());
        int countByName = adoptMapper.selectCount(queryWrapper);
        log.debug("根据相册名称统计匹配的相册数量，结果：{}", countByName);
        if (countByName > 0){
            String message = "添加宠物领养失败，已有此领养记录";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        Adopt adopt = new Adopt();
        BeanUtils.copyProperties(adoptAddNewParam,adopt);
        adopt.setGmtCreate(LocalDateTime.now());
        adopt.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的宠物领养数据写入到数据库，数据：{}", adopt);
        int rows = adoptMapper.insert(adopt);
        if (rows != 1){
            String message = "添加宠物领养请求失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的宠物领养数据写入到数据库，完成！");
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【删除宠物领养】的业务，参数：{}", id);
        // 检查该领养记录是否存在，如果不存在，则抛出异常
        QueryWrapper<Adopt> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = adoptMapper.selectCount(queryWrapper);
        log.debug("根据宠物领养ID统计匹配的宠物领养数量，结果：{}", countById);
        if (countById == 0) {
            String message = "删除宠物领养失败，宠物领养数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

//        QueryWrapper<Pet> queryWrapper2 = new QueryWrapper<>();
//        queryWrapper2.eq("id", id);
//        int countByAlbumId2 = petMapper.selectCount(queryWrapper2);
//        log.debug("根据相册ID统计匹配的图片数量，结果：{}", countById);
//        if (countByAlbumId2 > 0) {
//            String message = "删除宠物领养失败，仍有宠物关联到此相册！";
//            log.warn(message);
//            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
//        }

        int rows = adoptMapper.deleteById(id);
        if (rows != 1){
            String message = "删除宠物领养失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.debug("从数据库删除一条数据，完成！");
    }

    @Override
    public void updateInfoById(Long id,
                               AdoptUpdateInfoParam adoptUpdateInfoParam) {
        log.debug("开始处理【修改宠物领养详情】的业务，ID：{}，新数据：{}", id, adoptUpdateInfoParam);
        QueryWrapper<Adopt> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = adoptMapper.selectCount(queryWrapper);
        log.debug("根据宠物领养ID统计匹配的宠物领养数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改宠物领养详情失败，宠物领养数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        Adopt adopt = new Adopt();
        BeanUtils.copyProperties(adoptUpdateInfoParam, adopt);
        adopt.setId(id);
        int rows = adoptMapper.updateById(adopt);
        if (rows != 1){
            String message = "修改宠物领养失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("将新的宠物领养数据更新入到数据库，完成！");
    }

    @Override
    public void agreeAdoptById(Long id) {
        log.debug("开始处理【同意宠物领养】的业务，ID：{}", id);

        AdoptStandardVO adoptData = adoptMapper.getStandardById(id);
        //判断该请求记录装填值是否1
        Integer adoptState = adoptData.getState();
        if (adoptState==1){
            String message = "该领养记录已审核过，不可重复审核";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_PET_RECHECK, message);
        }

        //判断宠物是否被领养
        Long petId = adoptData.getPetId();
        Integer petState = petMapper.getStandardById(petId).getState();
        if (petState==1){
            String message ="该宠物已被领养，不可再次申请!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_PET_ADOPTED, message);
        }
        int rows = adoptMapper.updateState(id);
        if (rows != 1){
            String message = "修改宠物领养失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        petMapper.updateState(petId);
        log.debug("将新的宠物领养数据更新入到数据库，完成！");
        AdoptRecord adoptRecord = new AdoptRecord();
        adoptRecord.setAdoptId(id);
        adoptRecord.setRemark(null);
        adoptRecord.setSort(99);
        adoptRecord.setGmtCreate(LocalDateTime.now());
        adoptRecord.setGmtModified(LocalDateTime.now());
        adoptRecordMapper.insert(adoptRecord);

        //修改adopt中的记录的状态值为1
        adoptMapper.updateState(id);
        log.debug("处理同意宠物领养申请记录完成！");
    }

    @Override
    public void disAgreeAdoptById(Long id,String remark) {
        log.debug("开始处理【不同意宠物领养】的业务，ID：{}，原因：{}", id,remark);

        AdoptStandardVO adoptData = adoptMapper.getStandardById(id);
        //判断该请求记录装填值是否1
        Integer adoptState = adoptData.getState();
        if (adoptState==1){
            String message = "该领养记录已审核过，不可重复审核";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_PET_RECHECK, message);
        }

        //判断宠物是否被领养
        Long petId = adoptData.getPetId();
        Integer petState = petMapper.getStandardById(petId).getState();
        if (petState==1){
            String message ="该宠物已被领养，不可再次申请!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_PET_ADOPTED, message);
        }
        int rows = adoptMapper.updateState(id);
        if (rows != 1){
            String message = "修改宠物领养失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
//        petMapper.updateState(petId);
        log.debug("将新的宠物领养数据更新入到数据库，完成！");
        AdoptRecord adoptRecord = new AdoptRecord();
        adoptRecord.setAdoptId(id);
        adoptRecord.setRemark(remark);
        adoptRecord.setSort(99);
        adoptRecord.setGmtCreate(LocalDateTime.now());
        adoptRecord.setGmtModified(LocalDateTime.now());
        adoptRecordMapper.insert(adoptRecord);

        //修改adopt中的记录的状态值为1
        adoptMapper.updateState(id);
        log.debug("处理不同意宠物领养申请记录完成！");

    }

    @Override
    public AdoptStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询宠物领养详情】的业务，参数：{}", id);
        AdoptStandardVO queryResult = adoptMapper.getStandardById(id);
        if (queryResult == null){
            String message = "查询宠物领养详情失败，宠物领养数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public PageData<AdoptListVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<AdoptListVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询相册列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<AdoptListVO> list = adoptMapper.list();
        PageInfo<AdoptListVO> pageInfo = new PageInfo<>(list);
        PageData<AdoptListVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

}
